package com.beiming.libra.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.beiming.libra.common.Assert;
import com.beiming.libra.common.constants.ExcelConstants;
import com.beiming.libra.common.constants.NotificationMessages;
import com.beiming.libra.common.enums.ArbitrationCaseLogUserStatusEnum;
import com.beiming.libra.common.enums.ArbitrationCaseLogWorkStatusEnum;
import com.beiming.libra.common.enums.ArbitrationCaseStatusEnum;
import com.beiming.libra.common.enums.CaseApplyEnum;
import com.beiming.libra.common.enums.CaseUserTypeEnum;
import com.beiming.libra.common.enums.ErrorCode;
import com.beiming.libra.common.enums.UserTypeEnum;
import com.beiming.libra.common.enums.VerifyEnum;
import com.beiming.libra.common.utils.BeanConvertUtils;
import com.beiming.libra.common.utils.BigDecimalUtils;
import com.beiming.libra.common.utils.CommonsUtils;
import com.beiming.libra.common.utils.ErrorBean;
import com.beiming.libra.common.utils.ExcelBean;
import com.beiming.libra.common.utils.ExcelReaderUtil;
import com.beiming.libra.common.utils.FileUtil;
import com.beiming.libra.common.utils.GlobalUtil;
import com.beiming.libra.common.utils.UnZipFileUtil;
import com.beiming.libra.dao.ArbUserDetailMapper;
import com.beiming.libra.dao.ArbitrationBusinessDisputesMapper;
import com.beiming.libra.dao.ArbitrationCaseDocumentMapper;
import com.beiming.libra.dao.ArbitrationCaseLogMapper;
import com.beiming.libra.dao.ArbitrationCaseMapper;
import com.beiming.libra.dao.ArbitrationCaseUserMapper;
import com.beiming.libra.dao.CaseUserDetailMapper;
import com.beiming.libra.dao.CaseUserRelationMapper;
import com.beiming.libra.dao.UserDetailMapper;
import com.beiming.libra.dao.UserMapper;
import com.beiming.libra.domain.ArbUserDetail;
import com.beiming.libra.domain.ArbitrationBusinessDisputes;
import com.beiming.libra.domain.ArbitrationCase;
import com.beiming.libra.domain.ArbitrationCaseDocument;
import com.beiming.libra.domain.ArbitrationCaseLog;
import com.beiming.libra.domain.ArbitrationCaseUser;
import com.beiming.libra.domain.CaseUserDetail;
import com.beiming.libra.domain.CaseUserRelation;
import com.beiming.libra.domain.FileInfo;
import com.beiming.libra.domain.User;
import com.beiming.libra.domain.UserDetail;
import com.beiming.libra.domain.UserMessage;
import com.beiming.libra.domain.dto.requestdto.caseapply.ArbitrationCaseUserRequestDTO;
import com.beiming.libra.domain.dto.requestdto.caseapply.CaseApplyRequestDTO;
import com.beiming.libra.domain.dto.requestdto.caseapply.CaseUserRequestDTO;
import com.beiming.libra.domain.dto.requestdto.caseapply.DisputeRequestDTO;
import com.beiming.libra.domain.dto.requestdto.caseapply.MultiAddCaseRequestDTO;
import com.beiming.libra.domain.dto.responsedto.FileUploadResponseDTO;
import com.beiming.libra.domain.dto.responsedto.caseapply.MutiAddCaseResponseDTO;
import com.beiming.libra.service.CaseApplyService;
import com.beiming.libra.service.FileService;
import com.beiming.libra.service.UserMessageService;
import com.beiming.libra.service.UserService;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * 案件书面审理service
 *
 * @author tp Date : 2018/6/5/005 9:17
 */
@Service
public class CaseApplyServiceImpl implements CaseApplyService {

  @Resource
  private ArbitrationBusinessDisputesMapper arbitrationBusinessDisputesMapper;

  @Resource
  private ArbitrationCaseDocumentMapper arbitrationCaseDocumentMapper;

  @Resource
  private ArbitrationCaseMapper arbitrationCaseMapper;

  @Resource
  private UserMapper userMapper;
  @Resource
  private UserDetailMapper userDetailMapper;
  @Resource
  private ArbitrationCaseUserMapper arbitrationCaseUserMapper;

  @Resource
  private CaseUserDetailMapper caseUserDetailMapper;
  @Resource
  private FileService fileService;
  @Resource
  private UserService userService;
  @Resource
  private UserMessageService userMessageService;
  @Resource
  private ArbUserDetailMapper arbUserDetailMapper;

  @Resource
  private CaseUserRelationMapper caseUserRelationMapper;

  @Resource
  private ArbitrationCaseLogMapper arbitrationCaseLogMapper;

  @Value("${file.storage.root.dir}")
  private String storageRootDir;

  @Value("${file.storage.tmp.dir}")
  private String storageTmpDir;
  @Value("${file.storage.prefix}")
  private String prefix;


  private Logger logger = LoggerFactory.getLogger(CaseApplyServiceImpl.class);

  @Override
  public int insertBusinessDisputes(ArbitrationBusinessDisputes arbitrationBusinessDisputes) {
    return this.arbitrationBusinessDisputesMapper.insertSelective(arbitrationBusinessDisputes);
  }

  @Override
  public int insertArbitrationCaseDocumentList(
      List<ArbitrationCaseDocument> arbitrationCaseDocumentList, String caseId) {
    Assert.isListNotEmpty(arbitrationCaseDocumentList, ErrorCode.ILLEGAL_PARAMETER);
    arbitrationCaseDocumentList.forEach(arbitrationCaseDocument -> {
      arbitrationCaseDocument.setId(CommonsUtils.get32BitUUID());
      arbitrationCaseDocument.setCaseId(caseId);
    });
    return this.arbitrationCaseDocumentMapper.insertList(arbitrationCaseDocumentList);
  }

  @Override
  public List<DisputeRequestDTO> selectDisputeType(Integer type) {
    List<DisputeRequestDTO> disputeRequestDTOList = new ArrayList<>();
    if (CaseApplyEnum.NONFINANCIAL.getCode().equals(type)) {
      return new ArrayList<DisputeRequestDTO>();
    } else {
      List<Map<String, Object>> mapByGroup = CaseApplyEnum.getMapByGroup(2);
      mapByGroup.forEach(map -> {
        DisputeRequestDTO disputeRequestDTO = new DisputeRequestDTO();
        disputeRequestDTO.setDisputeType(Integer.parseInt(map.get("code") + ""));
        disputeRequestDTO.setDisputeTypeName(map.get("name") + "");
        disputeRequestDTOList.add(disputeRequestDTO);
      });
      return disputeRequestDTOList;
    }
  }

  @Override
  public Boolean authentication(String currentUserId) {
    User user = this.userMapper.selectByPrimaryKey(currentUserId);
    Assert.isNotNull(user, ErrorCode.ILLEGAL_PARAMETER);
    if (VerifyEnum.YES.getCode().equals(user.getIsRealName())) {
      return true;
    }
    return false;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public int insertArbitrationCase(CaseApplyRequestDTO caseApplyRequestDTO, String userId) {
    // 案件基本信息
    String caseId = CommonsUtils.get32BitUUID();
    ArbitrationCase arbitrationCase = BeanConvertUtils
        .copyBean(caseApplyRequestDTO.getArbitrationCaseRequest(), ArbitrationCase.class);
    arbitrationCase.setId(caseId);
    // 生成案件号，案件名称
    String caseName = this.createCaseName(arbitrationCase.getDisputeType(),
        caseApplyRequestDTO.getArbitrationCaseUserRequestList());
    String caseNo = GlobalUtil.getGlobalId();
    arbitrationCase.setCaseName(caseName);
    arbitrationCase.setCaseNo(caseNo);
    arbitrationCase.setCaseStatus(ArbitrationCaseStatusEnum.APPLY_REVIEW.getCode());
    arbitrationCase.setWorkStatus(ArbitrationCaseLogWorkStatusEnum.APPLY_REVIEW.getName());
    arbitrationCase.setUserStatus(ArbitrationCaseLogUserStatusEnum.APPLY_REVIEW.getName());
    //业务纠纷要素
    ArbitrationBusinessDisputes arbitrationBusinessDisputes = BeanConvertUtils
        .copyBean(caseApplyRequestDTO.getArbitrationBusinessDisputes(),
            ArbitrationBusinessDisputes.class);
    arbitrationBusinessDisputes.setId(CommonsUtils.get32BitUUID());
    arbitrationBusinessDisputes.setCaseId(caseId);
    //证据材料
    List<ArbitrationCaseDocument> arbitrationCaseDocuments = BeanConvertUtils
        .copyList(caseApplyRequestDTO.getArbitrationCaseDocumentList(),
            ArbitrationCaseDocument.class);
    arbitrationCaseDocuments.forEach(arbitrationCaseDocument -> {
      arbitrationCaseDocument.setId(CommonsUtils.get32BitUUID());
      arbitrationCaseDocument.setCaseId(caseId);
    });
    //案件关联人员
    List<ArbitrationCaseUser> arbitrationCaseUsers = BeanConvertUtils
        .copyList(caseApplyRequestDTO.getArbitrationCaseUserRequestList(),
            ArbitrationCaseUser.class);
    //处理用户关系表，发送消息
    this.processCaseUser(arbitrationCaseUsers, caseId, caseName);
    //保存业务纠纷要素
    this.insertBusinessDisputes(arbitrationBusinessDisputes);
    //保存证据材料
    this.arbitrationCaseDocumentMapper.insertList(arbitrationCaseDocuments);
    //分配办案秘书
    arbitrationCase = this.createArbUser(arbitrationCase);
    // 案件信息
    List<ArbitrationCase> arbitrationCases = new ArrayList<>();
    arbitrationCases.add(arbitrationCase);
    return this.insertCaseList(arbitrationCases);
  }


  @Override
  @Transactional(rollbackFor = Exception.class)
  public List<MutiAddCaseResponseDTO> multiAddCase(MultiAddCaseRequestDTO multiAddCaseRequestDTO,
      HttpServletRequest request)
      throws Exception {
    FileUploadResponseDTO fileUploadResponseDTO = fileService
        .upload(multiAddCaseRequestDTO.getFile(), "批量上传案件", request);
    String remoteFileName = fileUploadResponseDTO.getRemoteFileName();
    //解压文件
    String zipPath = this.storageRootDir + remoteFileName;
    //解压至路径
    String destFilePath = this.storageRootDir;
    //最终生成文件名称(去除后缀)
    String originPath = remoteFileName.substring(0, remoteFileName.lastIndexOf("."));
    //解压文件操作
    UnZipFileUtil.unZip(zipPath, destFilePath + originPath + "/");
    String originFileName = fileUploadResponseDTO.getOriginFileName();
    //解压之后文件路径
    String lastFilePath = this.storageRootDir + originPath + "/" + originFileName
        .substring(0, originFileName.lastIndexOf(".")) + "/";
    //解析excel文件
    Map<String, Object> resultMap = ExcelReaderUtil
        .parseExcel(lastFilePath + ExcelConstants.CASEXLS);
    List<ErrorBean> errorList = (List<ErrorBean>) resultMap.get("errorList");
    //判断excel解析是否有错直接返回
    if (!CollectionUtils.isEmpty(errorList)) {
      List<MutiAddCaseResponseDTO> mutiAddCaseResponseDTOS = BeanConvertUtils
          .copyList(errorList, MutiAddCaseResponseDTO.class);
      //删除解压文件
      FileUtil.deletAllFiles(this.storageRootDir + originPath);
      return mutiAddCaseResponseDTOS;
    }
    List<ExcelBean> excelBeanList = (List<ExcelBean>) resultMap.get("excelBean");
    //定义证据list
    List<ArbitrationCaseDocument> arbitrationCaseDocuments = new ArrayList<>();
    List<CaseUserDetail> caseUserDetailList = new ArrayList<>();
    List<UserDetail> userDetails = new ArrayList<>();
    List<ArbitrationCase> arbitrationCaseList = new ArrayList<>();
    List<ArbitrationBusinessDisputes> arbitrationBusinessDisputesList = new ArrayList<>();
    List<ArbitrationCaseUser> arbitrationCaseUserList = new ArrayList<>();
    List<User> userList = new ArrayList<>();
    List<FileInfo> fileInfoList = new ArrayList<>();
    //根据生成的excel 文件进行相应的解析文件
    excelBeanList.forEach(excelBean -> {
      // 生成案件id
      String caseId = CommonsUtils.get32BitUUID();
      String caseNo = GlobalUtil.getGlobalId();
      //封装案件信息
      ArbitrationCase arbitrationCase = new ArbitrationCase();
      arbitrationCase.setId(caseId);
      arbitrationCase.setCaseNo(caseNo);
      arbitrationCase = this.createRequestItem(arbitrationCase, excelBean, multiAddCaseRequestDTO);
      // 封装纠纷要素
      ArbitrationBusinessDisputes arbitrationBusinessDisputes = new ArbitrationBusinessDisputes(
          excelBean, caseId);
      Map<String, Object> userMap = this
          .createCaseUser(excelBean, caseId, arbitrationCase.getCaseName());
      //处理证据材料问题
      JSONObject jsonObject = this.createArbitionCaseDocument(lastFilePath, excelBean,
          caseId);
      //纠纷要素
      arbitrationBusinessDisputesList.add(arbitrationBusinessDisputes);
      //案件信息
      arbitrationCaseList.add(arbitrationCase);
      //证据材料
      arbitrationCaseDocuments.addAll(jsonObject.getObject("arbitrationCaseDocument", List.class));
      //案件人员详情
      caseUserDetailList.add((CaseUserDetail) userMap.get("caseUserDetail"));
      //案件关联人员
      arbitrationCaseUserList.add((ArbitrationCaseUser) userMap.get("arbitrationCaseUser"));
      //用户详情
      userDetails.add((UserDetail) userMap.get("userDetail"));
      //用户
      userList.add((User) userMap.get("user"));
      //保存附件信息
      fileInfoList.addAll(jsonObject.getObject("fileInfo", List.class));
    });
    //数据入库处理
    this.caseUserDetailMapper.insertCaseUserList(caseUserDetailList);
    //保存案件关联人员,以及发送消息
    this.arbitrationCaseUserMapper.insertList(arbitrationCaseUserList);
    this.arbitrationCaseDocumentMapper.insertList(arbitrationCaseDocuments);
    this.fileService.insertFileInfo(fileInfoList);
    this.arbitrationBusinessDisputesMapper.insertList(arbitrationBusinessDisputesList);
    // 批量添加案件信息
    this.insertCaseList(arbitrationCaseList);
    //处理用户中心
    this.userService.insertListUser(userList, userDetails);
    //处理完成之后将解压文件删除
    FileUtil.deletAllFiles(this.storageRootDir + originPath);
    return null;
  }

  @Override
  public Map<String, Object> getEvidenceType() {
    List<Map<String, Object>> mapByGroup = CaseApplyEnum.getMapByGroup(3);
    Map<String, Object> resultMap = new HashMap<>();
    resultMap.put("evidenceType", mapByGroup);
    return resultMap;
  }

  /**
   * 添加案件，日志
   */
  private int insertCaseList(List<ArbitrationCase> arbitrationCases) {
    arbitrationCases.forEach(arbitrationCase -> {
      ArbitrationCaseLog arbitrationCaseLog = new ArbitrationCaseLog("0", arbitrationCase.getId(),
          ArbitrationCaseLogUserStatusEnum.APPLY_REVIEW.getName(),
          ArbitrationCaseStatusEnum.APPLY_REVIEW.getCode());
      ArbitrationCaseLog arbitrationCaseLog1 = new ArbitrationCaseLog("1", arbitrationCase.getId(),
          ArbitrationCaseLogUserStatusEnum.APPLY_REVIEW.getName(),
          ArbitrationCaseStatusEnum.APPLY_REVIEW.getCode());
      this.arbitrationCaseLogMapper.insertSelective(arbitrationCaseLog);
      this.arbitrationCaseLogMapper.insertSelective(arbitrationCaseLog1);
    });
    return this.arbitrationCaseMapper.insertCaseList(arbitrationCases);
  }

  /**
   * 处理批量立案附件
   */
  private JSONObject createArbitionCaseDocument(String lastFilePath,
      ExcelBean excelBean,
      String caseId) {
    List<ArbitrationCaseDocument> arbitrationCaseDocuments = new ArrayList<>();
    List<FileInfo> fileInfoList = new ArrayList<>();
    JSONObject resultMap = new JSONObject();
    // 获取归档编号
    String archive = excelBean.getArchive();
    // 对应附件路径
    String filepath = lastFilePath + archive + "/";
    // 处理对应的证据附件信息
    File file = new File(filepath);
    File[] files = file.listFiles();
    for (int i = 0; i < files.length; i++) {
      if (!files[i].isDirectory()) {
        String filename = files[i].getName();
        String suffix = filename.substring(filename.lastIndexOf("."));
        String remoteFileName = CommonsUtils.get32BitUUID() + suffix;
        files[i].renameTo(new File(this.storageRootDir + remoteFileName));
        //生成对应的附件url
        String url = this.prefix + remoteFileName;
        String fileId = CommonsUtils.get32BitUUID();
        ArbitrationCaseDocument arbitrationCaseDocument = new ArbitrationCaseDocument(caseId,
            files[i].getName(), url, fileId);
        FileInfo fileInfo = new FileInfo();
        fileInfo.setId(CommonsUtils.get32BitUUID());
        fileInfo.setFileUrl(url);
        fileInfo.setOriginFileName(filename);
        fileInfo.setRemoteFileName(remoteFileName);
        fileInfo.setFilePath(this.storageRootDir + remoteFileName);
        arbitrationCaseDocuments.add(arbitrationCaseDocument);
        fileInfoList.add(fileInfo);
      }
    }
    resultMap.put("arbitrationCaseDocument", arbitrationCaseDocuments);
    resultMap.put("fileInfo", fileInfoList);
    return resultMap;
  }

  /**
   * 处理用户相关逻辑
   */
  private Map<String, Object> createCaseUser(ExcelBean excelBean, String caseId, String caseName) {
    //案件关联人员详情
    String userId = CommonsUtils.get32BitUUID();
    CaseUserDetail caseUserDetail = BeanConvertUtils.copyBean(excelBean, CaseUserDetail.class);
    caseUserDetail.setCaseId(caseId);
    caseUserDetail.setUserId(userId);
    caseUserDetail.setUserType(UserTypeEnum.PEOPLE.getCode());
    caseUserDetail.setId(CommonsUtils.get32BitUUID());
    //案件关联人员关系表
    ArbitrationCaseUser arbitrationCaseUser = new ArbitrationCaseUser();
    arbitrationCaseUser.setId(CommonsUtils.get32BitUUID());
    arbitrationCaseUser.setAddUserStatus("1");
    arbitrationCaseUser.setCaseId(caseId);
    arbitrationCaseUser.setUserId(userId);
    arbitrationCaseUser.setUserType(CaseUserTypeEnum.RESPONDENT.getCode());
    arbitrationCaseUser.setCaseName(caseName);
    // 用户
    User user = new User();
    user.setId(userId);
    user.setMobilePhone(excelBean.getMobilePhone());
    user.setUserType(UserTypeEnum.PEOPLE.getCode());
    // 用户详情
    UserDetail userDetail = BeanConvertUtils.copyBean(caseUserDetail, UserDetail.class);
    Map<String, Object> jsonObject = new HashMap<>();
    jsonObject.put("user", user);
    jsonObject.put("userDetail", userDetail);
    jsonObject.put("caseUserDetail", caseUserDetail);
    jsonObject.put("arbitrationCaseUser", arbitrationCaseUser);
    return jsonObject;
  }


  /**
   * 拼装生成请求事项和理由
   *
   * @param arbitrationCase 案件
   * @param excelBean excel解析数据
   */
  private ArbitrationCase createRequestItem(ArbitrationCase arbitrationCase, ExcelBean excelBean,
      MultiAddCaseRequestDTO multiAddCaseRequestDTO) {
    // 本金以及利息
    //计算标的总额
    BigDecimal targetAmount = BigDecimalUtils
        .add(excelBean.getInterests(), excelBean.getPrincipal());
    // 请求事项
    String requestItem = String
        .format(ExcelConstants.REQUEST_ITEM, targetAmount, excelBean.getPrincipal(),
            excelBean.getInterests(), excelBean.getTime());
    arbitrationCase.setRequestItem(requestItem);
    //事实与理由
    String factandReason = String
        .format(ExcelConstants.FACTANDREASON, excelBean.getDateOfContract(),
            excelBean.getContactName(), excelBean.getContactNo(), excelBean.getPrincipal(),
            excelBean.getBillDate());
    arbitrationCase.setFactAndReason(factandReason);
    arbitrationCase.setDisputeType(multiAddCaseRequestDTO.getDisputeType());
    arbitrationCase.setCaseType(multiAddCaseRequestDTO.getCaseType());
    arbitrationCase.setCaseName(excelBean.getUserName() + " " + CaseApplyEnum
        .getName(Integer.parseInt(multiAddCaseRequestDTO.getDisputeType())));
    arbitrationCase.setTargetAmount(targetAmount);
    arbitrationCase.setCaseStatus(ArbitrationCaseStatusEnum.APPLY_REVIEW.getCode());
    arbitrationCase.setWorkStatus(ArbitrationCaseLogWorkStatusEnum.APPLY_REVIEW.getName());
    arbitrationCase.setUserStatus(ArbitrationCaseLogWorkStatusEnum.APPLY_REVIEW.getName());
    //分配办案秘书
    return this.createArbUser(arbitrationCase);
  }

  /**
   * 生成案件名称（第一个申请人+案件类型）
   *
   * @param caseType 案件类型
   */
  private String createCaseName(String caseType,
      List<ArbitrationCaseUserRequestDTO> arbitrationCaseUserRequestDTOList) {
    ArbitrationCaseUserRequestDTO arbitrationCaseUserRequestDTO = arbitrationCaseUserRequestDTOList
        .stream().filter(e -> CaseUserTypeEnum.APPLICANT.getCode().equals(e.getUserType()))
        .collect(Collectors.toList()).get(0);
    return arbitrationCaseUserRequestDTO.getRealName() + "  " + CaseApplyEnum
        .getName(Integer.parseInt(caseType), 2);
  }

  /**
   * 处理案件关联人员
   */
  private void processCaseUser(List<ArbitrationCaseUser> arbitrationCaseUsers, String caseId,
      String caseName) {
    List<ArbitrationCaseUser> arbitrationCaseUserList = new ArrayList<>();
    List<String> userIds = new ArrayList<>();
    arbitrationCaseUsers.forEach(caseUser -> {
      caseUser.setAddUserStatus("1");
      caseUser.setCaseName(caseName);
      caseUser.setId(CommonsUtils.get32BitUUID());
      caseUser.setCaseId(caseId);
      List<CaseUserRequestDTO> proxys = caseUser.getProxys();
      proxys.forEach(proxyUser -> {
        ArbitrationCaseUser arbitrationCaseUser = BeanConvertUtils
            .copyBean(proxyUser, ArbitrationCaseUser.class);
        arbitrationCaseUser.setId(CommonsUtils.get32BitUUID());
        arbitrationCaseUser.setCaseId(caseId);
        arbitrationCaseUser.setCaseName(caseName);
        CaseUserRelation caseUserRelation = new CaseUserRelation();
        caseUserRelation.setCaseId(caseId);
        caseUserRelation.setProxyId(proxyUser.getUserId());
        caseUserRelation.setUserId(caseUser.getUserId());
        caseUserRelation.setId(CommonsUtils.get32BitUUID());
        // 保存用户关系表
        this.caseUserRelationMapper.insert(caseUserRelation);
        arbitrationCaseUserList.add(arbitrationCaseUser);
        userIds.add(proxyUser.getUserId());
      });
      userIds.add(caseUser.getUserId());
      arbitrationCaseUserList.add(caseUser);
    });
    // 根据userId查询添加的用户
    Example example = new Example(UserDetail.class);
    example.setDistinct(true);
    Criteria criteria = example.createCriteria();
    criteria.andIn("userId", userIds);
    List<UserDetail> userDetails = this.userDetailMapper.selectByExample(example);
    Assert.isListNotEmpty(userDetails, ErrorCode.ILLEGAL_PARAMETER);
    List<CaseUserDetail> caseUserDetails = BeanConvertUtils
        .copyList(userDetails, CaseUserDetail.class);
    List<CaseUserDetail> caseUserDetailList = new ArrayList<>();
    caseUserDetails.forEach(caseUserDetail -> {
      caseUserDetail.setId(CommonsUtils.get32BitUUID());
      caseUserDetail.setCaseId(caseId);
      caseUserDetailList.add(caseUserDetail);
    });
    // 新增案件关联人员信息
    this.caseUserDetailMapper.insertCaseUserList(caseUserDetailList);
    // 保存用户关系表
    this.arbitrationCaseUserMapper.insertList(arbitrationCaseUserList);
  }

  /**
   * 分配办案秘书
   */
  private ArbitrationCase createArbUser(ArbitrationCase arbitrationCase) {
    Example example = new Example(ArbUserDetail.class);
    Criteria criteria = example.createCriteria();
    criteria.andEqualTo("userType", UserTypeEnum.SECRETARY.getCode());
    criteria.andLike("ability", "%{}%".replace("{}", ExcelConstants.WELLDO));
    List<ArbUserDetail> arbUserDetails = arbUserDetailMapper.selectByExample(example);
    if (!CollectionUtils.isEmpty(arbUserDetails)) {
      int size = arbUserDetails.size();
      ArbUserDetail arbUserDetail = arbUserDetails.get((int) Math.random() * size);
      String userId = arbUserDetail.getUserId();
      arbitrationCase.setSecretaryId(userId);
      UserMessage userMessage = new UserMessage(arbitrationCase.getId(), userId,
          ExcelConstants.TITLE,
          String.format(NotificationMessages.SECRET_MESSAGES, arbitrationCase.getCaseName()));
      this.userMessageService.insertUserMessage(userMessage);
    }
    return arbitrationCase;
  }


}
